<!-- 多图片上传 -->
<template>
    <el-upload v-model:file-list="state.fileList" :action="data.actionUrl" :headers="data.headers" list-type="picture-card"
        :on-success="handleAvatarSuccess" :on-preview="handlePictureCardPreview" :limit="data.limit"
        :on-remove="handleRemove" :before-upload="beforeAvatarUpload">
        <el-icon>
            <Plus />
        </el-icon>
        <template #tip>
            <div class="el-upload__tip">
                {{ data.tip }}
            </div>
        </template>
    </el-upload>
    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const emit = defineEmits(['uploadImageClick'])
import type { UploadProps, UploadUserFile } from 'element-plus'
const props = defineProps({
    data: {
        type: Object,
        default: () => { }
    }
})
const state = reactive({
    fileList: [] as any
})
function fileUrl(data) {
    data.forEach(element => {
        state.fileList.push(element)
    });
}
function fileUrls(data) {
    
    let array = ""
    for (let index = 0; index < data.length; index++) {
        if (index == 0) {
            array = data[index].response.data.ossId
        } else {
            array = array + "," + data[index].response.data.ossId
        }
    }
    return array
}
fileUrl(props.data.urls)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log("多图片删除成功", uploadFile, uploadFiles)
    emit('uploadImageClick', fileUrls(state.fileList))
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log("多图片上传成功：", response, uploadFile);
    emit('uploadImageClick', fileUrls(state.fileList))
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片格式有误! 仅支持jpg、jpeg、png格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > (props.data.size ? props.data.size : 2)) {
        ElMessage.error(`图片大小不超过${props.data.size ? props.data.size : 2}MB!`)
        return false
    }
    return true
}
</script>